package com.fx.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser;
import net.minidev.json.JSONObject;

import java.util.Map;

/**
 * @Auther: EDZ
 * @Date: 2018-6-1 10:05:
 * @Email: 你的邮箱
 * 概要说明：该类干嘛用的
 **/
public class JWTUtil {
    //可有无，随意设置的属性值
    private static final String BAOSIGHT_SHORTNAME = "kdpche";
    //站点秘钥
    private static final String BAOSIGHT_SECRET = "3d990d2276917dfac04467df11fff26d";


    public static String getToken(String id, String openId, String userName) {
        JSONObject userInfo = new JSONObject();
        //用户id(用户在网站中的唯一标示)
        userInfo.put("user_key", id);
        //网站二级域名
        userInfo.put("short_name", BAOSIGHT_SHORTNAME);
        //用户名
        userInfo.put("name", userName);//可选项
        userInfo.put("openId", openId);//可选项
        userInfo.put("expireTime", System.currentTimeMillis());//可选项
        Payload payload = new Payload(userInfo);
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
        JWSObject jwsObject = new JWSObject(header, payload);
        try {
            JWSSigner signer = new MACSigner(BAOSIGHT_SECRET.getBytes());
            jwsObject.sign(signer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jwsObject.serialize();
    }

    public static com.alibaba.fastjson.JSONObject parseToken(String token) {
        try {
            JWT jwt = JWTParser.parse(token);
            JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();
            Map<String, Object> map = jwtClaimsSet.getClaims();
            return new com.alibaba.fastjson.JSONObject(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {


        System.out.println(getToken("2323232323","2","xiaomin"));

    }
}
